package com.example.administrator.basedemos.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.adapter.BlutoothItemAdapter;
import com.example.administrator.basedemos.base.BaseActivity;

import java.util.ArrayList;
import java.util.Set;

import butterknife.BindView;

/**
 * 创建者     ZCL
 * 创建时间   2018/5/4 14:58
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class BlutoothActivity extends BaseActivity {
    private static final int    REQUEST_ENABLE = 1;
    private static final String TAG            = "BlutoothActivity";
    @BindView(R.id.blutooth_recyclerview)
    RecyclerView mBlutoothRecyclerview;
    @BindView(R.id.blutooth_recyclerview_show)
    TextView     mBlutoothRecyclerviewShow;
    private BlutoothItemAdapter mAdapter;
    private BluetoothAdapter    mBluetoothAdapter;
    private BluetoothManager    mBluetoothManager;
    private BroadcastReceiver   mBluetoothReceiver;

    @Override
    public void initView() {
        mBlutoothRecyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mBlutoothRecyclerview.setItemAnimator(new DefaultItemAnimator());

        ArrayList<String> list = new ArrayList<>();
        list.add(getString(R.string.open_blutooth));
        list.add(getString(R.string.search_blutooth));
        list.add(getString(R.string.close_blutooth));
        list.add(getString(R.string.visiable_blutooth));
        list.add(getString(R.string.linked));
        list.add(getString(R.string.linked_finish));

        mAdapter = new BlutoothItemAdapter(R.layout.item_blutooh, list);
        mBlutoothRecyclerview.setAdapter(mAdapter);
    }

    @Override
    public void initData() {

        //如果设备支持BLE，那么就可以获取蓝牙适配器。
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = mBluetoothManager.getAdapter();
        } else {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }

        IntentFilter filter = new IntentFilter();
        //发现设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //设备连接状态改变
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        //蓝牙设备状态改变
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mBluetoothReceiver = new BlutoothReceiver();
        registerReceiver(mBluetoothReceiver, filter);

        if (mAdapter != null)
            mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    switch (position) {
                        case 0:
                            break;
                        case 1://搜索
                            searchBlutooth();
                            break;
                        case 2://停止搜索
                            mBluetoothAdapter.cancelDiscovery();
                            break;
                        case 3:
                            //蓝牙可见可见性的时间由EXTRA_DISCOVERABLE_DURATION设定，取值范围在0~3600秒之间，
                            // 当设置为0的时候表示蓝牙设备永远可见，如果设置的时间不在0~3600之间，时间会被默认设置为300秒。
                            // 如果在设置可见性，蓝牙设备没有打开，设备将会被自动打开！！！
                            Intent leIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                            leIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                            startActivity(leIntent);
                            break;

                        default:
                            break;
                    }
                }
            });
    }

    private void openBlutooth() {
        if (!mBluetoothAdapter.isEnabled()) {
            //弹出对话框提示打开 直接使用 enable方法有些手机会出错
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE);
        }
    }

    private void searchBlutooth() {
        if (mBluetoothAdapter != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
            mBluetoothAdapter.startDiscovery();
        }
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_blutooth;
    }

    private class BlutoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "mBluetoothReceiver action =" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //每扫描到一个设备，系统都会发送此广播。
                //获取蓝牙设备
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (scanDevice == null || scanDevice.getName() == null)
                    return;
                //蓝牙设备名称
                Log.d(TAG, "name=" + scanDevice.getName() + "address=" + scanDevice.getAddress());
                //取消扫描
                mBluetoothAdapter.cancelDiscovery();

                //获取本机蓝牙名称
                String name = mBluetoothAdapter.getName();
                //获取本机蓝牙地址
                String address = mBluetoothAdapter.getAddress();
                Log.d(TAG, "bluetooth name =" + name + " address =" + address);
                //获取已配对蓝牙设备
                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                Log.d(TAG, "bonded device size =" + devices.size());

                for (BluetoothDevice bonddevice : devices) {
                    Log.d(TAG, "bonded device name =" + bonddevice.getName() + " address" + bonddevice.getAddress());
                }
               //try {
               //   // BluetoothSocket clientSocket = scanDevice.createRfcommSocketToServiceRecord(new UUID(410074));
               //    // 阻塞直到服务器接受连接
               //   // clientSocket.connect();
               //    //可以先发送消息
               //    //开始监听消息
               //    StringBuilder incoming = new StringBuilder();
               //    //listenForMessages(clientSocket, incoming);
               //    // 添加对用于发送信息的套接字的引用
               //    //transferSocket = clientSocket;
               //} catch (IOException e) {
               //    Log.e("蓝牙", "蓝牙客户端 I/O 出错", e);
               //}
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d(TAG, "搜索已结束");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothReceiver);
    }
}

